#include "drv_tim_basic.h"
#include "drv_sysclk.h"
#include <mm32f327xx_hal_config.h>

HAL_TIM_Basic_InitType htim;

void Drv_TIM_Basic_Init(void)
{
    /* Set the counter counting step. */
    TIM_CLK_EN();
    htim.Instance = TIM_PORT;
    htim.init.ClockFreqHz = HAL_GetSysClockFreq();
    htim.init.StepFreqHz = 1000; /* set the step. */
    htim.init.Period = 1000 - 1u; /* set the period. */
    htim.init.EnablePreloadPeriod = false;
    htim.init.PeriodMode = TIM_BASIC_PeriodMode_OneTimeRun;  /* continus mode */
    TIM_BASIC_Init(htim.Instance, &htim.init);

    /* Enable interrupt. */
    NVIC_EnableIRQ(TIM_IRQn);
    TIM_BASIC_EnableInterrupts(htim.Instance, TIM_BASIC_INT_UPDATE_PERIOD, true);
}

void HAL_TIM_Basic_StartOnce(HAL_TIM_Basic_InitType *tim, uint16_t once_time)
{
    TIM_BASIC_Stop(tim->Instance);
    HAL_TIM_Basic_SetPeriod(tim->Instance, once_time);
    TIM_BASIC_Start(tim->Instance);
}

__WEAK void HAL_TIM_Basic_PeriodElapsedCallback(HAL_TIM_Basic_InitType *tim)
{
    /* reimp;ement this function */
}

void HAL_TIM_Basic_IRQHandler(HAL_TIM_Basic_InitType *tim)
{
    uint32_t flags = TIM_BASIC_GetInterruptStatus(tim->Instance);
    if ( 0u != (flags & TIM_BASIC_STATUS_UPDATE_PERIOD ) )
    {
        HAL_TIM_Basic_PeriodElapsedCallback(tim);
    }
    TIM_BASIC_ClearInterruptStatus(tim->Instance, flags);
}

void TIM_IRQHandler(void)
{
    HAL_TIM_Basic_IRQHandler(&htim);
}
